<!DOCTYPE html>
<html lang="en">
  <head>
    <meta charset="UTF-8" />
    <meta http-equiv="X-UA-Compatible" content="IE=edge" />
    <meta name="viewport" content="width=device-width, initial-scale=1.0" />
    <title>Document</title>
  </head>

  <body>
    <form>
      <input
        type="file"
        name="avatar"
        accept="image/*"
        placeholder="请选择头像"
      />
      <button>上传文件</button>
    </form>
    <img src="" alt="" class="avatar" style="width: 500px" />
  </body>
  <script src="./js/axios.js"></script>
  <script>
    //获取元素
    const form = document.querySelector('form')
    const avatar = document.querySelector('.avatar')

    //绑定事件
    form.addEventListener('submit', function (e) {
      //阻止默认提交行为
      e.preventDefault()

      //获取头像的文件
      const fd = new FormData(this)

      console.log(fd.get('avatar'))

      // 发起请求
      async function response(){
       const { data: res }= await axios({
        url: 'http://ajax-api.itheima.net/api/file',
        method: 'POST',
        data: fd,
      })
      console.log(res);
      const url = res.data.url
        avatar.src = url
      }
      response()
      // axios({
      //   url: 'http://ajax-api.itheima.net/api/file',
      //   method: 'POST',
      //   data: fd,
      // }).then(({ data: res }) => {
      //   const url = res.data.url
      //   avatar.src = url
      // })
      // axios.post('http://ajax-api.itheima.net/api/file', fd).then()
    })
  </script>
</html>
